﻿using System;
using System.ComponentModel;
using System.Reflection;

namespace FastMVVM.Core
{
    /// <summary>
    /// Represents a dynamic object that provides notifications when has any property changed.
    /// </summary>
    public class ObservableObject : INotifyPropertyChanged
    {
        /// <summary>
        /// Occurs when any property change of value.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;


        /// <summary>
        /// Check if the property really exists.
        /// </summary>
        /// <param name="propertyName"></param>
        private void checkPropertyName(String propertyName)
        {
            Type myType = this.GetType();
            PropertyInfo prop = myType.GetProperty(propertyName);

            if (prop == null)
                throw new ArgumentException("The property \"" + propertyName + "\" is not a member of \"" + myType.Name + "\" class.");
        }


        /// <summary>
        /// Call the PropertyChanged notification.
        /// Need be called at any property's set struture.
        /// </summary>
        /// <param name="propertyName">The name of the property that has changed.</param>
        public void NotifyPropertyChanged(String propertyName)
        {
            checkPropertyName(propertyName);

            if (PropertyChanged != null)
            {
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
